package com.example.newleadcent.leadcent;

import com.alibaba.fastjson.JSONObject;
import com.example.newleadcent.entity.Location;
import com.example.newleadcent.entity.Point;
import com.example.newleadcent.entity.Realtime;
import com.example.newleadcent.entity.Term;
import com.example.newleadcent.service.LocationService;
import com.example.newleadcent.service.PointService;
import com.example.newleadcent.service.RealtimeService;
import com.example.newleadcent.service.TermService;
import com.example.newleadcent.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class LeadcentDecoder {
    @Autowired
    private TermService termService;
    @Autowired
    private LocationService locationService;
    @Autowired
    private PointService pointService;
    @Autowired
    private RealtimeService realtimeService;

    static private  LeadcentDecoder leadcentDecoder;
    @PostConstruct
    public void init(){
        leadcentDecoder = this;
    }


    private String Imei;
    private String type;
    private String[] content;

    private byte[] response = {0x00};

    public String getImei() {
        return Imei;
    }

    public byte[] getResponse() {
        return response;
    }

    public void decode(String data){

        String [] data_arr = data.split(",");
        type = data_arr[1];
        Imei = data_arr[2];
        content = new String[data_arr.length-6];
        System.arraycopy(data_arr, 3, content, 0, data_arr.length-6);

        if(type.equals("0001")){
            String[] s = register(content);
            response = toData(type, Imei, s);

        }else if(type.equals("0004")){
            String[] time ={"TIME",DateUtils.dateTimeNow("yyMMddHHmmss")};
            response = toData(time,"1004");

        }else if(type.equals("0005")){
            Location location = new Location();
            Term term = leadcentDecoder.termService.getTerminfoByImei(Imei);

            location.setterm_imei(Imei);
            term.setterm_imei(Imei);
            term.setchainstate(1);
            term.setbatvalue(80);
            term.setterm_state(0);

            String alarm = content[content.length-1];
            System.out.println("报警： "+alarm);
            if(!alarm.equals("")){
                String[] alarmNum = alarm.split("A");
                for(int i=0; i<alarmNum.length; i++){
                    //拆卸报警
                    if(alarmNum[i].equals("11")){
                        term.setchainstate(0);
                        //拆卸
                    }

                    //低电量报警
                    if(alarmNum[i].equals("14")){
                        //term.setbatvalue(15);//低电
                    }
                    if(alarmNum[i].equals("7")){
                        term.setchainstate(0);
                        term.setbatvalue(15);//拆卸，低电
                    }
                    //关机报警
                    if(alarmNum[i].equals("8")){
                        term.setterm_state(4);//关机

                    }
                }
            }

            String locationType = content[0];
            String rmc = null;
            String lbs = null;
            String wifi = null;
            String location_lat = null;
            String location_lng = null;
            String location_name = null;
            int type = 0;


            if(locationType.equals("A")){       //混合定位
                rmc = content[3];
                lbs = content[5];
                wifi = content[6];
                System.out.println("rmc: "+rmc);
                System.out.println("lbs: "+lbs);
                System.out.println("wifi: "+wifi);
            }else if(locationType.equals("S")){ //卫星定位RMC
                rmc = content[3];
                System.out.println("rmc: "+rmc);
            }else if(locationType.equals("M")){ //基站定位lbs
                lbs = content[3];
                System.out.println("lbs: "+lbs);
            }else if(locationType.equals("W")){ //wifi定位
                wifi = content[3];
                System.out.println("wifi: "+wifi);
            }

            //wifi和gps定位都不太准，尽量用基站
            if(lbs!=null && lbs.length()!=0){
                String[] lbs_arr = lbs.split("/");
                String mnc = lbs_arr[0];
                String lac = lbs_arr[1];
                String cell = lbs_arr[2];
                JSONObject jsonObject = LbsAPI.getLocJSON("460",mnc,lac,cell);

                if(jsonObject.getString("errcode").equals("0")){
                    location_lat = jsonObject.getString("lat");
                    location_lng = jsonObject.getString("lon");
                    location_name = jsonObject.getString("address");
//                    location_name = BaiduAPI.getLocName(location_lat,location_lng);
                    type = 4;
                }
            }else if(rmc != null && rmc.length() != 0){
                String[] rmc_arr = rmc.split("/");
                String latstr = rmc_arr[2];                 //度分形式     ddmm.mmmmmm
                String lat_type = rmc_arr[3];
                String lngstr = rmc_arr[4];
                String lng_type = rmc_arr[5];

                double lat = GPSUtil.parseLat(latstr,lat_type);  //度形式(转换坐标专用)  dd.dddddd
                double lng = GPSUtil.parseLng(lngstr,lng_type);
                System.out.println("谷歌坐标系："+lat+","+lng);

                double[] bd = GPSUtil.gps84_To_bd09(lat, lng);      //谷歌坐标系化为百度坐标系
                location_name = BaiduAPI.getLocName(String.valueOf(bd[0]),String.valueOf(bd[1]));
                location_lat = String.valueOf(bd[0]);
                location_lng = String.valueOf(bd[1]);
                type = 1;
            }


//
//            if(rmc!=null && !rmc.equals("")){           //既不是null也不是""
//                String[] rmc_arr = rmc.split("/");
//                String latstr = rmc_arr[2];                 //度分形式     ddmm.mmmmmm
//                String lat_type = rmc_arr[3];
//                String lngstr = rmc_arr[4];
//                String lng_type = rmc_arr[5];
//
//                double lat = GPSUtil.parseLat(latstr,lat_type);  //度形式(转换坐标专用)  dd.dddddd
//                double lng = GPSUtil.parseLng(lngstr,lng_type);
//                System.out.println("谷歌坐标系："+lat+","+lng);
//
//                double[] bd = GPSUtil.gps84_To_bd09(lat, lng);      //谷歌坐标系化为百度坐标系
//                location_name = BaiduAPI.getLocName(String.valueOf(bd[0]),String.valueOf(bd[1]));
//                location_lat = String.valueOf(bd[0]);
//                location_lng = String.valueOf(bd[1]);
//                type = 1;
//
//            }
//            else if(wifi!=null && !wifi.equals("")){
//                String[] wifi_arr = wifi.split("/");
//                String wifi_final = "";
//                for(int i=0; i<wifi_arr.length; i=i+2){
//                    String macs = "";
//                    char[] tmp = wifi_arr[i].toCharArray();
//                    for(int j=0; j<tmp.length; j=j+2){
//                        if(j!=tmp.length-2)  macs = macs + tmp[j] + tmp[j+1] + ":";
//                        else macs = macs + tmp[j] + tmp[j+1];
//                    }
//                    System.out.println("macs: "+macs);
//
//                    if(i == 0) wifi_final = macs + "," + wifi_arr[i+1] + ",TPLink";
//                    else wifi_final = wifi_final + "|" + macs + "," + wifi_arr[i+1] + ",TPLink";
//
//                }
//
//                JSONObject locJSON = GaodeAPI.getLocByWifi(Imei, wifi_final);
//                if(!locJSON.getJSONObject("result").getString("type").equals("0")){
//                    String[] data_arrr = locJSON.getJSONObject("result").getString("location").split(",");
//                    location_lat = data_arrr[1];
//                    location_lng = data_arrr[0];
//                    location_name = locJSON.getJSONObject("result").getString("desc");
//                    type = 2;
//                }
//
//            }
//            else if(lbs!=null && !lbs.equals("")){       //没有信号值，用不了高德API
//                String[] lbs_arr = lbs.split("/");
//                String mnc = lbs_arr[0];
//                String lac = lbs_arr[1];
//                String cell = lbs_arr[2];
//                JSONObject jsonObject = LbsAPI.getLocJSON("460",mnc,lac,cell);
//
//                if(jsonObject.getString("errcode").equals("0")){
//                    location_lat = jsonObject.getString("lat");
//                    location_lng = jsonObject.getString("lon");
//                    //location_name = jsonObject.getString("address");
//                    location_name = BaiduAPI.getLocName(location_lat,location_lng);
//                    type = 4;
//                }
//            }

            if(location_lat!=null && location_name!=null){             //存数据库
                System.out.println("lat: "+location_lat);
                System.out.println("lng: "+location_lng);
                System.out.println("name: "+location_name);

                location.setlocation_lat(location_lat);
                location.setlocation_lng(location_lng);
                location.setlocation_name(location_name);
                location.setLocation_type(type);
                location.setlocation_time(DateUtils.getTime());
                leadcentDecoder.locationService.add(location);

                term.setlocation_lat(location_lat);
                term.setlocation_lng(location_lng);
                term.setlocation_name(location_name);
                term.setlocation_time(DateUtils.getTime());
                term.setlocation_type(type);
                leadcentDecoder.termService.update(term);

                UploadUtil.uploadToConverter(term);                     //将数据传给转发器

//                Point point = new Point();                                                        //在实时数据库中创建Point点
//                point.setRT(4);
//                point.setGN("W3.LOCATION." + Imei + "_LNG");
//                leadcentDecoder.pointService.insert(point);                                         //插入经度Point点
//                point.setGN("W3.LOCATION." + Imei + "_LAT");                                      //插入纬度Point点
//                leadcentDecoder.pointService.insert(point);
//
//                Realtime realtime = new Realtime();
//                realtime.setGN("W3.LOCATION." + Imei + "_LNG");
//                realtime.setAV(Double.valueOf(location_lng));                      //------当s_lng为null的时候有空指针异常
//                leadcentDecoder.realtimeService.insert(realtime);
//                realtime.setGN("W3.LOCATION." + Imei + "_LAT");
//                realtime.setAV(Double.valueOf(location_lat));
//                leadcentDecoder.realtimeService.insert(realtime);                 //在实时数据库中插入经纬度

            }

            String[] par=new String[1];
            par[0]="PARAMETER";
            response = toData("1012",this.Imei, par);

        }

    }

    /*
            为啥term不需要更新的，
            面向切面那个有啥用
     */


    public String[] register(String[] content){
        if(leadcentDecoder.termService.getTerminfoByImei(Imei) == null){
            Term term = new Term();
            term.setterm_imei(Imei);
            term.setterm_provider(2);
            term.setregister_time(DateUtils.getTime());
            int i = leadcentDecoder.termService.add(term);
            System.out.println("注册： "+i);
        }

        return new String[]{content[0],"OK"};
    }

    public byte[] toData(String[] content, String type){
        return toData(type, Imei, content);
    }

    public byte[] toData(String type, String Imei, String[] contents){
        String output = "$HX," + type + "," + Imei + ",";
        for(int i=0; i<contents.length; i++){
            output += contents[i];
            output += ",";
        }
        output += "#";
        String s = FormatUtil.checksum_String(output);
        output = output + "," + s + "," + "\r\n";

        return output.getBytes();
    }


}
